<script setup lang="ts">
    import { ref, watch } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { useCountDown } from '@vant/use'
    import { joinTechAPIRes, sendSmsApi, getqiniuTokenApi } from '@/api'
    import { useLocation } from '@/store/location'
    import { ataURLtoBlob } from '@/utils'
    import axios from 'axios'
    import dayjs from 'dayjs'
    import joinTechBg from '@/assets/images/joinTechBg.png'
    import idCode from '@/assets/images/idCode.png'
    import idCode2 from '@/assets/images/idCode2.png'

    const { query } = useRoute()
    const router = useRouter()
    const userStore = useLocation()
    const showPicker = ref(false)
    const validatorMessage = ref('')
    const isDisable = ref(false)
    const uploadName = ref<any>('')
    const formData = ref<any>({
        nickname: '',
        username: '',
        mobile: '',
        sendSms: '',
        workTime: '',
        settledCity: userStore.city,
        introduce: '',
        idcard1: '',
        idcard2: ''
    })
    const countDown = useCountDown({ time: 60 * 1000, onFinish: () => {
        isDisable.value = false
        countDown.reset()
    } })
    const current = countDown.current

    const onSendSms = async () => {
        if (!formData.value.mobile) {
            validatorMessage.value = '请填写手机号码'
            return
        }
        const { code } = await sendSmsApi({ mobile: formData.value.mobile })
        if (code == 0) {
            isDisable.value = true
            countDown.start()
        }
    }
    // 上传
    const onUpload = (idcard: string) => {
        uploadName.value = idcard
    }
    const afterRead = async (file: any) => {
        const { data } = await getqiniuTokenApi()
        const qiniuToken = data.uploadToken
        const fileData = JSON.parse(JSON.stringify(file))
        let imageBase64 = ''
        if (fileData.content.indexOf('data:image') == 0) {
            //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
            imageBase64 = fileData.content
        } else {
            //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
            //此时一个正常的base64图片路径就完美生成赋值到img的src中了
            imageBase64 = 'data:image/jpeg;base64,' + fileData.content.replace(/\n/g, '')
        }
        const imgData = new FormData()
        imgData.append('file', ataURLtoBlob(imageBase64))
        imgData.append('token', qiniuToken)
        imgData.append("key", dayjs().valueOf().toString())
        axios.post(import.meta.env.VITE_BASE_QINIU, imgData, {
            headers: { "Content-Type": "multipart/form-data" }
        }).then(async res => {
            formData.value[uploadName.value] = import.meta.env.VITE_BASE_QINIU_IMG + res.data.key
        })
    }
    const onSubmit = async () => {
        await joinTechAPIRes(formData.value)
    }

    watch([() => userStore.city], () => {
        formData.value.settledCity = userStore.city
    })
</script>

<template>
    <div class="min-h-dvh bg-gradient-to-b from-[#a3e4ed] from-[12.5rem] to-white">
        <van-nav-bar v-if="query.t" left-arrow fixed safe-area-inset-top :border="false" class="bg-none" @click-left="router.back()" />
        <van-image width="100%" height="12.5rem" fit="cover" :src="joinTechBg" />
        <van-form @submit="onSubmit" class="mt-[-2rem]">
            <van-cell-group inset class="mx-2.5">
                <van-field
                    v-model.trim="formData.nickname"
                    clearable
                    required
                    center
                    label="平台昵称"
                    placeholder="请输入平台昵称"
                    :rules="[{ required: true, message: '请输入平台昵称' }]"
                />
                <van-field
                    v-model.trim="formData.username"
                    clearable
                    required
                    center
                    label="真实姓名"
                    placeholder="请输入真实姓名"
                    :rules="[{ required: true, message: '请输入真实姓名' }]"
                />
                <van-field
                    v-model.trim="formData.mobile"
                    clearable
                    required
                    center
                    type="tel"
                    label="手机号码"
                    placeholder="请输入手机号码"
                    :rules="[{ required: true, message: '请输入手机号码' }]"
                    :error-message="validatorMessage"
                />
                <van-field
                    v-model="formData.sendSms"
                    required
                    center
                    clearable
                    type="digit"
                    label="短信验证码"
                    placeholder="请输入短信验证码"
                    :rules="[{ required: true, message: '请输入短信验证码' }]"
                >
                    <template #button>
                        <van-button size="small" color="#7C6186" :disabled="isDisable" @click="onSendSms">
                            <span v-if="!isDisable">发送验证码</span>
                            <span v-else>{{ current.seconds }}s</span>
                        </van-button>
                    </template>
                </van-field>
                <van-field
                    v-model="formData.workTime"
                    required
                    center
                    clearable
                    type="digit"
                    label="工作经验"
                    placeholder="请输入工作经验"
                    :rules="[{ required: true, message: '请输入工作经验' }]"
                >
                    <template #extra>年</template>
                </van-field>
                <van-field
                    v-model="formData.settledCity"
                    is-link
                    required
                    readonly
                    label="入驻城市"
                    placeholder="选择入驻城市"
                    @click="showPicker = true"
                />
                <van-field
                    v-model="formData.introduce"
                    rows="2"
                    autosize
                    label="自我介绍"
                    type="textarea"
                    placeholder="请输入自我介绍"
                    show-word-limit
                    label-align="top"
                />
            </van-cell-group>
            <van-cell-group inset class="mt-3 mx-2.5">
                <van-field label="上传身份证照片" label-align="top">
                    <template #input>
                        <div class="w-full flex items-center justify-between text-center text-sm">
                            <div class="flex-1 mr-2">
                                <van-uploader :file-list="formData.idcard1" :after-read="afterRead" @click-upload="onUpload('idcard1')" :preview-size="['100%', '5.625rem']" max-count="1" class="w-full joinTech">
                                    <van-image width="100%" fit="cover" :src="formData.idcard1 || idCode" />
                                </van-uploader>
                                <div>身份证正面</div>
                            </div>
                            <div class="flex-1 ml-2">
                                <van-uploader :file-list="formData.idcard2" :after-read="afterRead" @click-upload="onUpload('idcard1')" :preview-size="['100%', '5.625rem']" max-count="1" class="w-full joinTech">
                                    <van-image width="100%" fit="cover" :src="formData.idcard2 || idCode2" />
                                </van-uploader>
                                <div>身份证反面</div>
                            </div>
                        </div>
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group inset class="my-3 mx-3 bg-inherit van-safe-area-bottom">
                <van-button round block color="#7C6186" native-type="submit">提交</van-button>
            </van-cell-group>
        </van-form>
    </div>
</template>

<style>
    .joinTech .van-uploader__wrapper {
        display: block;
    }
    .joinTech .van-uploader__preview {
        margin: 0;
    }
</style>